package com.vic.priorityqueue.controller;

import com.vic.priorityqueue.config.PriorityConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 生产者
 */
@Slf4j
@RestController
@RequestMapping("producer")
public class ProducerController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg/{msg}")
    public void sendMsg(@PathVariable String msg) {
        // 设置唯一 ID
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());

        rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, msg, correlationData);
        log.info("发送一条未设置优先级的消息", msg);

        String msg1 = msg + 0;
        rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, msg1, (message -> {
            message.getMessageProperties().setPriority(0);
            return message;
        }), correlationData);
        log.info("发送一条优先级为 0 的消息", msg1);

        String msg2 = msg + 2;
        rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, msg2, (message -> {
            message.getMessageProperties().setPriority(2);
            return message;
        }), correlationData);
        log.info("发送一条优先级为 2 的消息", msg2);

        String msg3 = msg + 5;
        rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, msg3, (message -> {
            message.getMessageProperties().setPriority(5);
            return message;
        }), correlationData);
        log.info("发送一条优先级为 5 的消息", msg3);

        String msg4 = msg + 10;
        rabbitTemplate.convertAndSend(PriorityConfig.PRIORITY_EXCHANGE, PriorityConfig.PRIORITY_ROUTING_KEY, msg4, (message -> {
            message.getMessageProperties().setPriority(10);
            return message;
        }), correlationData);
        log.info("发送一条优先级为 10 的消息", msg4);
    }

}
